<template>
  <div>
    <van-nav-bar title="密码修改" left-text="返回" left-arrow @click-left="() => $router.go(-1)" />
    <van-form>
      <van-field v-model="param.phone" name="用户名" label="用户名" placeholder="请输入账号" />
      <van-field v-model="param.sms" name="验证码" label="验证码" placeholder="请输入验证码">
        <template #button>
          <van-button v-if="hasSend" size="small" type="warning " disabled>{{ time }}s可重新发送</van-button>
          <van-button v-else size="small" type="primary" @click="sendCode()" :disabled="!canSendCode">发送验证码
          </van-button>
        </template>
      </van-field>
      <van-field v-model="param.password" name="密码" label="密码" placeholder="请输入新密码" />
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit" size="large" color="blue" :loading="subLoading"
          @click="savePass()" :disabled="!canSub">确认修改</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Notify } from "vant"

export default {
  data() {
    return {
      param: {
        phone: '',
        sms: '',
        password: ''
      },
      subLoading: false,
      hasSend:false,
      time:60
    }
  },
  methods: {
    //确认修改
    savePass() {
      this.subLoading = true
      this.$axios.post('/users/setPassword', this.param).then(res => {
        if (res.code === 200) {
          Notify({ type: 'success', message: '修改成功' })
          this.$router.replace("/mine");
        } else {
          Notify({ type: 'danger', message: '好像出了点问题' })
        }
        this.subLoading = false
      })
    },
    sendCode(){
      this.$axios.post(`/users/sendCode?phone=${this.param.phone}`).then((res) => {
        console.log("验证码", res);
      });
      this.hasSend = true
      let timer = setInterval(() => {
        this.time--
        if (this.time === 0) {
          clearInterval(timer)
          this.hasSend = false
          this.time = 60
        }
      }, 1000)
    }
  },
  computed: {
    canSub() {
      return Boolean(this.param.phone && this.param.sms && this.param.password)
    },
    canSendCode(){
      return Boolean(this.param.phone)
    }
  }
}
</script>

<style scoped>
</style>
